//
//  JLSViewController.m
//  瀑布流
//
//  Created by 焦林生 on 15/12/1.
//  Copyright © 2015年 jiaolinsheng. All rights reserved.
//

#import "JLSViewController.h"
#import "JLSClothes.h"
#import "JLSClothesCell.h"
#import "HMWaterfallFlowLayout.h"
#import <MJExtension.h>
#import <MJRefresh.h>

@interface JLSViewController ()<HMWaterfallFlowLayoutDelegate>
@property (nonatomic, strong) NSMutableArray *clothesArray;
@end

@implementation JLSViewController

static NSString * const reuseIdentifier = @"ClothesCell";

#pragma  mark - 懒加载
- (NSMutableArray *)clothesArray {

    if (_clothesArray == nil) {
        _clothesArray = [[NSMutableArray alloc] init];
    }
    return _clothesArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //加载数据
    NSArray *array = [JLSClothes mj_objectArrayWithFilename:@"clothes.plist"];
  
    [self.clothesArray addObjectsFromArray:array];
    
    //切换布局
    HMWaterfallFlowLayout *layout = [[HMWaterfallFlowLayout alloc] init];
    layout.delegate = self;
    self.collectionView.collectionViewLayout = layout;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    __weak typeof(self) weakSelf = self;
    // 刷新数据
    self.collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 加载数据
        NSArray *tempArray = [JLSClothes mj_objectArrayWithFilename:@"clothes.plist"];
        [weakSelf.clothesArray insertObjects:tempArray atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, tempArray.count)]];
        [weakSelf.collectionView reloadData];
        
        // 结束刷新
        [weakSelf.collectionView.mj_header endRefreshing];
    }];
    
    self.collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        // 加载数据
        NSArray *tempArray = [JLSClothes mj_objectArrayWithFilename:@"clothes.plist"];
        [weakSelf.clothesArray addObjectsFromArray:tempArray];
        [weakSelf.collectionView reloadData];
        
        // 结束刷新
        [weakSelf.collectionView.mj_footer endRefreshing];
    }];
    
}




#pragma mark <HMWaterfallFlowLayoutDelegate>
- (CGFloat)waterfallFlowLayout:(HMWaterfallFlowLayout *)layout heightForItemAtIndexPath:(NSIndexPath *)indexPath withItemWidth:(CGFloat)width {
    JLSClothes *clothes = self.clothesArray[indexPath.item];
    return clothes.h * width / clothes.w;
}

- (NSUInteger)columnCountInWaterfallFlowLayout:(HMWaterfallFlowLayout *)layout {
    return 3;
}

#pragma mark <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.clothesArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    JLSClothesCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    cell.clothes = self.clothesArray[indexPath.item];
    return cell;
}

@end
